package com.ctsi.security.service;

import com.ctsi.commons.event.EventPublisherMan;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.security.ISecurity;
import com.ctsi.security.PermissionSer;
import com.ctsi.security.PermissionTypeSer;
import com.ctsi.security.domain.Permission;
import com.ctsi.security.domain.PermissionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.util.*;


/**
 * 实现对系统功能类型的CRUD操作
 * 
 * @author zhangjw
 * 
 */
@Repository
public class PermissionTypeService implements PermissionTypeSer {
    @Autowired
	private MybatisGenericDao dao;
	private EventPublisherMan publisherMan;
    @Autowired
	private PermissionSer permissionService;
    @Autowired
	private ISecurity security;
	String dataObjectTye = "sysModule";
	String action = "SELECT";
	
	/**
	 * 构造函数
	 */
	public PermissionTypeService() {

	}

	/**
	 * 构造函数
	 * 
	 * @param myBatisGenericDao
	 */
	public PermissionTypeService(MybatisGenericDao myBatisGenericDao) {
		this.dao = myBatisGenericDao;
	}

	public void setDao(MybatisGenericDao myBatisGenericDao) {
		this.dao = myBatisGenericDao;
	}

	/**
	 * 保存对象
	 * 
	 * @param
	 */
	public void savePermissionType(PermissionType permissionType) {
		Assert.notNull(permissionType);
		String permissionTypeId = permissionType.getId();
		if (UtilValidate.isEmpty(permissionTypeId)) {
			permissionType.setId(UUID.randomUUID().toString());
		}
		dao.insert(permissionType);
		 
	}

	@Override
	public void updatePermissionType(PermissionType permissionType) {
		// dao.updateObject(permissionType);
		dao.update(permissionType);
	}

	@Override
	public void removePermissionType(PermissionType permissionType) {
		dao.remove(permissionType);
		 
	}
	
	@Override
	public void removePermissionType(String id) {
		PermissionType pt = new PermissionType();
		pt.setId(id);
		dao.remove(pt);
 
	}

	@Override
	public int[] removePermissionType(String[] arrayId, String[] arrayPermTypeId) {
		int[] ret = { -1, -1 };
		for (int i = 0; i < arrayId.length; i++) {
			// 查询该类型下是否有系统功能
			List<Permission> listPermission = permissionService.findPermission(new String[] { "permissionTypeId" }, new Object[] { arrayPermTypeId[i] });
			if (listPermission.size() > 0) {
				ret[0] = i;
				return ret;
			}
			// 查询该类型下是否有子类型
			List<PermissionType> listPermissionType = this.findPermissionType(new String[] { "parentId" }, new Object[] { arrayPermTypeId[i] });
			if (listPermissionType.size() > 0) {
				ret[1] = i;
				return ret;
			}
			// dao.removeObject(com.gentlesoft.security.domain.PermissionType.class,
			// arrayId[i]);
			removePermissionType(arrayId[i]);
			// 查询是否有功能类型数据对象对应关系有则删除

		}
		return ret;
	}

	@Override
	public Page queryPermissionType(int pageSize, int startIndex) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(PermissionType.class.getName());
		stringBuilder.append(".selectByMap");
		return dao.queryPage(stringBuilder.toString(), Collections.EMPTY_MAP, startIndex, pageSize);
 
	}

	@Override
	public Page<PermissionType> queryPermissionType(String userLoginId, String dataObjectType, String action, String permissionTypeId, String permissiontypeName, int pageSize, int startIndex) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (UtilValidate.isNotEmpty(permissionTypeId)) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("%");
			stringBuilder.append(permissionTypeId);
			stringBuilder.append("%");
			params.put("permissionTypeId", stringBuilder.toString());
		}
		if (UtilValidate.isNotEmpty(permissiontypeName)) {
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("%");
			stringBuilder.append(permissiontypeName);
			stringBuilder.append("%");
			params.put("permissiontypeName", stringBuilder.toString());
		}
		if (security.isControl(userLoginId, dataObjectType, action)) {
			List<String> dataObectIds = security.getDataObjectIds(userLoginId, dataObjectType, action);
			if (UtilValidate.isEmpty(dataObectIds)) {
				return new Page<PermissionType>();
			}
			if (dataObectIds.size() == 1) {
				params.put("dataObjectsId", dataObectIds.get(0));
			} else {
				params.put("dataObjectsIds", dataObectIds);
			}
		}
		return dao.queryPage(PermissionType.class.getName() + ".queryLikeSer", params, startIndex, pageSize);

		//		
		//		
		// Page<PermissionType> result = new Page();// 返回结果
		// StringBuilder builder = new StringBuilder();// HQL语句Builder
		// List<Object> params = new LinkedList<Object>();// HQL语句参数List
		// builder.append("from PermissionType");
		// builder.append(" where permissionTypeName like ?");
		// params.add("%".concat(permissiontypeName).concat("%"));
		// // 增加permissionTypeId查询条件
		// builder.append("and permissionTypeId like ?");
		// params.add("%".concat(permissionTypeId).concat("%"));
		// // 判断是否控制数据权限
		// if (!security.isControl(userLoginId, dataObjectType, action)) {
		// // 不控制数据权限
		// logger.info("{}查看功能类型不控制数据权限", userLoginId);
		// } else {
		// // 控制数据权限
		// List<String> list = security.getDataObjectIds(userLoginId,
		// dataObjectType, action);
		// // 判断是否为空
		// if (UtilValidate.isNotEmpty(list)) {// 不为空
		// logger.info("{}查询功能类型，其数据对象集为{}", userLoginId, dataObjectType);
		// // 判断长度是否为1
		// if (list.size() == 1) {// 为1
		// builder.append(" and dataObject=?");
		// params.add(list.get(0));
		// } else {// 大于1
		// // 凑？号
		// builder.append(" and dataObject in (?");
		// for (int i = 0; i < list.size() - 1; i++) {
		// builder.append(",?");
		// }
		// builder.append(")");
		// params.addAll(list);
		// }
		// } else {// 为空
		// logger.info("{}查询功能类型，数据对象集为空，没有返回结果");
		// return result;
		// }
		//
		// }
		// builder.append(" order by parentId");
		// logger.debug("HQL:{},params:{}", builder.toString(), params);
		// result = dao.findPageByQuery(builder.toString(), pageSize,
		// startIndex,
		// params.toArray());
		//
		// return result;
	}

 

	@Override
	public List<PermissionType> findPermissionTypeAll() {
		// String hql = "from com.gentlesoft.security.domain.PermissionType";
		// return dao.findAll(hql);
		return dao.find(PermissionType.class, Collections.EMPTY_MAP);
	}

	@Override
	public List<PermissionType> findPermissionType(String[] field, Object[] args) {
		// StringBuffer sbhql = new StringBuffer();
		// sbhql.append("from PermissionType");
		// for (int i = 0; i < field.length; i++) {
		// if (i == 0) {
		// sbhql.append(" where " + field[i] + "=?");
		// } else {
		// sbhql.append(" and " + field[i] + "=?");
		// }
		// }
		// return dao.findAll(sbhql.toString(), args);
		if (field == null || args == null) {
			return new ArrayList<PermissionType>(0);
		}
		Assert.isTrue(field.length == args.length, "arguments's length is not equal");
		Map<String, Object> params = new HashMap<String, Object>(field.length);
		for (int i = 0; i < field.length; i++) {
			params.put(field[i].toLowerCase(), args[i]);
		}
		return dao.find(PermissionType.class, params);

	}
	
	@Override
	public PermissionType findByPermisionTypeId(String typeId){
		return (PermissionType)dao.queryForObject(PermissionType.class.getName()+".findByPermisionTypeId", typeId);
	}

	// /**
	// * 分页查询数据 firstnode表示记录的起始点，从0开始 noderange表示需返回的总数，如果firstnode +
	// * noderange>纪录总数，则返回空的list
	// *
	// * @param field
	// * @param parameter
	// * @param firstnode
	// * @param noderange
	// * @return
	// */
	// public List<PermissionType> findPermissionType(String[] field,
	// Object[] args, int firstnode, int noderange) {
	// StringBuffer sbhql = new StringBuffer();
	// sbhql.append("from PermissionType");
	// for (int i = 0; i < field.length; i++) {
	// if (i == 0) {
	// sbhql.append(" where " + field[i] + "=?");
	// } else {
	// sbhql.append(" and " + field[i] + "=?");
	// }
	// }
	// return dao.findAll(sbhql.toString(), args, firstnode, noderange);
	// }

	// 得到父结点格式
	// public String findParentId(String id) {
	// StringBuffer sbParentCN = new StringBuffer();
	// // sbParentCN.append("[0,'根结点']");
	// String hql =
	// "from com.gentlesoft.security.domain.PermissionType where ID<>?";
	// List<PermissionType> listPerType = dao
	// .findAll(hql, new Object[] { id });
	// Iterator<PermissionType> itePerType = listPerType.iterator();
	// PermissionType perType = new PermissionType();
	// for (int i = 0; itePerType.hasNext(); i++) {
	// perType = itePerType.next();
	// sbParentCN.append("['" + perType.getPermissionTypeId() + "','"
	// + perType.getPermissionTypeName() + "'],");
	// }
	// sbParentCN.deleteCharAt(sbParentCN.length() - 1);
	// return sbParentCN.toString();
	// }

	// 取所有的系统资源
	@Override
	public String findPermissionType() {
		StringBuilder sbParentCN = new StringBuilder();
		sbParentCN.append("['','请选择']");
		// String hql = "from com.gentlesoft.security.domain.PermissionType";
		// List<PermissionType> listPerType = dao.findAll(hql);
		List<PermissionType> listPerType = this.findPermissionTypeAll();
		Iterator<PermissionType> itePerType = listPerType.iterator();
		PermissionType perType = new PermissionType();
		while (  itePerType.hasNext() ) {
			perType = itePerType.next();
			sbParentCN.append(",['" + perType.getPermissionTypeId() + "','" + perType.getPermissionTypeName() + "']");
		}
		return sbParentCN.toString();
	}
	@Override
	public boolean valPermTypeId(String permTypeId) {
		// String hql =
		// "from com.gentlesoft.security.domain.PermissionType where permissionTypeId=?";
		// List<PermissionType> listPerType = dao.findAll(hql,
		// new Object[] { permTypeId });
		List<PermissionType> listPerType = findPermissionType(new String[] { "permissiontypeid" }, new Object[] { permTypeId });
		if (listPerType.size() > 0) {
			return true;
		} else {
			return false;
		}
	}
	@Override
	public List<Permission> findAllChildPermision(String typeId,String loginId ){
		Map<String,Object> params=new HashMap<String, Object>(1);
		params.put("permissiontypeid", typeId);
		List<Permission> permissions = permissionService.findPermission(loginId, dataObjectTye, action,params);			
		List<PermissionType> allType =findAllChildPermisionType( typeId, loginId );		
		for(PermissionType permissionType:allType){
			params=new HashMap<String, Object>(1);
			params.put("permissiontypeid", permissionType.getPermissionTypeId());
			List<Permission> temp = permissionService.findPermission(loginId, dataObjectTye, action,params);	
			permissions.addAll(temp);
		}		
		return permissions;
	}
	
	@Override
	public List<PermissionType> findAllChildPermisionType(String typeId,String userLoginId ){

		List<PermissionType> allType = new ArrayList<PermissionType>();
		List<PermissionType> list =findAllSon( userLoginId,  dataObjectTye,  action,  typeId);
		allType.addAll(list);
		for(PermissionType permissionType :list){
			List<PermissionType> childs = findAllChildPermisionType( permissionType.getPermissionTypeId(), userLoginId );
			allType.addAll(childs);
		}
		return allType;
	}

	
	@Override
	public List<PermissionType> findAllSon(String parentId) {
		// String hql =
		// "from com.gentlesoft.security.domain.PermissionType where parentId=?";
		// return dao.findAll(hql, new Object[] { parentId });
		return findPermissionType(new String[] { "parentid" }, new Object[] { parentId });
	}

	
	@Override
	public List<PermissionType> findAllSon(String userLoginId, String dataObjectTye, String action, String parentId) {
		
		/*控制数据权限
		 * 
		 * */
		
		if (security.isControl(userLoginId, dataObjectTye, action)) {
			List<String> dataObjectIds = security.getDataObjectIds(userLoginId, dataObjectTye, action);
			if (UtilValidate.isEmpty(dataObjectIds)) {
				return new ArrayList<PermissionType>(0);
			}
			if (dataObjectIds.size() == 1) {
				return this.findPermissionType(new String[] { "parentId", "dataObjectsId" }, new Object[] { parentId, dataObjectIds.get(0) });
			} else {
				return this.findPermissionType(new String[] { "parentId", "dataObjectsIds" }, new Object[] { parentId, dataObjectIds });
			}
		} else {
			return this.findPermissionType(new String[] { "parentId" }, new Object[] { parentId });
		}
		// List<PermissionType> result = new ArrayList<PermissionType>();// 返回结果
		// // HQL语句
		// String hql = "from PermissionType where parentId=?";
		// // HQL语句参数
		// List<String> args = new LinkedList<String>();
		// args.add(parentId);
		// // 判断是否需要控制数据权限
		// if (!security.isControl(userLoginId, dataObjectTye, action)) {
		// // 不控制数据权限
		// logger.info("{}查询功能类型不控制数据权限for permissionId:{}", userLoginId,
		// dataObjectTye);
		// } else {// 控制数据权限
		// logger.info("{}查询功能类型控制数据权限for permissionId:{}", userLoginId,
		// dataObjectTye);
		// List<String> dataObjectIds = security.getDataObjectIds(userLoginId,
		// dataObjectTye, action);
		// // 判断列表是否为空
		// if (UtilValidate.isEmpty(dataObjectIds)) {
		// logger.info("{}查询功能类型，数据对象集为空", userLoginId);
		// return result;
		// }
		// logger.info("{}查询功能类型，数据对象集为{}", userLoginId, dataObjectIds);
		// // 判断列表长度是否为1
		// if (dataObjectIds.size() == 1) {// 等于1，不用IN操作
		// hql = hql.concat(" and dataObject=?");
		// args.add(dataObjectIds.get(0));
		// } else {// 大于1，使用IN操作
		// hql = hql.concat(" and dataObject in (?");
		// // 凑？号
		// for (int i = 0; i < dataObjectIds.size() - 1; i++) {
		// hql = hql.concat(",?");
		// }
		// hql = hql.concat(")");
		// args.addAll(dataObjectIds);
		// }
		//
		// }
		// result = dao.findAll(hql, args.toArray());// 返回结果
		// return result;
	}



	public void setPublisherMan(EventPublisherMan publisherMan) {
		this.publisherMan = publisherMan;
	}
	public void setPermissionService(PermissionSer permissionService) {
		this.permissionService = permissionService;
	}

	public void setSecurity(ISecurity security) {
		this.security = security;
	}

	public EventPublisherMan getPublisherMan() {
		return publisherMan;
	}
	@Override
	public String getDataObjectTye() {
		return dataObjectTye;
	}

	public void setDataObjectTye(String dataObjectTye) {
		this.dataObjectTye = dataObjectTye;
	}

	@Override
	public ISecurity getSecurity() {
		return security;
	}
}
